package provider.gateway;

import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 公共方法的基类
 * @author libra
 */
public class BaseController {
	public Map<String, String> getAllCookies( HttpServletRequest req ){
		Map<String, String> map = new HashMap<String, String>();
		Cookie[] cookies = req.getCookies();
		for( Cookie c : cookies ) {
			map.put(c.getName(), c.getValue());
		}
		return map;
	}
	
	public Map<String, String> getAllHeaders( HttpServletRequest req ){
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<String> headerNames = req.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String header = (String) headerNames.nextElement();
			map.put(header, req.getHeader(header));
		}
		return map;
	}
	
	public Map<String, String> getAllParams( HttpServletRequest req ){
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<String> parameterNames = req.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String paramKey = (String) parameterNames.nextElement();
			map.put(paramKey, Arrays.toString(req.getParameterValues(paramKey)));
		}
		return map;
	}
	
	public String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) 
            ip = request.getHeader("Proxy-Client-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("WL-Proxy-Client-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("HTTP_CLIENT_IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            ip = request.getRemoteAddr();
        return ip;
    }
}
